const fs = require('fs')
    , moment = require('moment')
    , superagent = require('superagent')
    , wxcfg = JSON.parse(fs.readFileSync( __dirname + '/config.json', 'utf-8'))
    , url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxcfg.appID}&secret=${wxcfg.appsecret}`

module.exports = function() {
    const cache = JSON.parse(fs.readFileSync( __dirname +  '/.cache.access_token.json', 'utf-8'))
    if (moment().unix() > cache.expires_in){
        return superagent
            .get(url)
            .then((res) => res.text)
            .then(function(str) {
                let obj =  JSON.parse(str)
                obj.expires_in = moment().add(2,'hours').unix() - 20
                return JSON.stringify(obj)})
            .then(function(data) {
                fs.writeFileSync( __dirname + '/.cache.access_token.json', data)
                return JSON.parse(data).access_token
            })
    }else{
        return cache.access_token
    }
}
